package com.metaapp.image.adapter

import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.FutureTarget
import com.metaapp.image.R
import com.metaapp.image.data.Image
import kotlinx.android.synthetic.main.view_image.view.*


/**
 * Created by huangshengsen on 2020/8/11.
 */
class ImageListAdapter(val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    enum class Type(val value: Int) {
        Data(0),
        Foot(1)
    }

    private var data = mutableListOf<Image>()
    private var onLoadMore: (() -> Unit)? = null
    private var isLoading = false
    fun setData(list: List<Image>) {
        data.clear()
        data.addAll(list)
        isLoading = false
        notifyDataSetChanged();
    }

    fun addData(list: List<Image>) {
        data.addAll(list)
        isLoading = false
        notifyDataSetChanged();
    }

    fun setOnloadMore(load: () -> Unit) {
        onLoadMore = load
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        if (viewType == Type.Data.value) {
            return ImageViewHolder(
                LayoutInflater.from(parent.context).inflate(
                    R.layout.view_image,
                    parent,
                    false
                )
            )
        } else {
            return FootViewHolder(
                LayoutInflater.from(parent.context).inflate(
                    R.layout.view_loading,
                    parent,
                    false
                )
            )
        }

    }

    override fun getItemCount(): Int {
        return data.size + 1
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == itemCount - 1) Type.Foot.value else Type.Data.value
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val type = getItemViewType(position)
        if (Type.Data.value == type) {
            (holder as ImageViewHolder).bind(data[position])
        } else {
            holder.itemView.visibility = if (itemCount == 1) View.INVISIBLE else View.VISIBLE
            if (!isLoading) {
                isLoading = true
                onLoadMore?.invoke()
            }

        }
    }


    inner class ImageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView = itemView.imageView
        val titleView = imageView.textView

        fun bind(image: Image) {
//            titleView.text = image.title
            Glide.with(context)
                .load(image.img)
                .into(imageView)

        }
    }

    class FootViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

}